package com.ohuang.demo.view

import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.method.KeyListener
import android.util.Log
import android.view.KeyEvent
import android.view.inputmethod.BaseInputConnection
import android.view.inputmethod.CompletionInfo
import android.view.inputmethod.CorrectionInfo
import android.view.inputmethod.ExtractedText
import android.view.inputmethod.ExtractedTextRequest
import android.view.inputmethod.InputMethodManager

class SimpleComposeInputConnection(textview: SimpleEditText) :
    BaseInputConnection(textview, true) {
    private val mTextInputView: SimpleEditText?
    protected val mIMM: InputMethodManager?
    private val TAG = "EditableInputConnection"
    private val DEBUG = true

    // Keeps track of nested begin/end batch edit to ensure this connection always has a
    // balanced impact on its associated TextView.
    // A negative value means that this connection has been finished by the InputMethodManager.
    private var mBatchEditNesting = 0

    init {
        mIMM = textview.context.getSystemService(
            Context.INPUT_METHOD_SERVICE
        ) as InputMethodManager
        mTextInputView = textview
    }

    override fun getSelectedText(flags: Int): CharSequence? {
        return super.getSelectedText(flags)
    }

    override fun getEditable(): Editable? {
        return mTextInputView?.editableText
    }
    override fun getExtractedText(request: ExtractedTextRequest, flags: Int): ExtractedText? {
        val et = ExtractedText()
        if (mTextInputView?.extractText(request, et) == true) {
            if (flags and GET_EXTRACTED_TEXT_MONITOR != 0) {
                mTextInputView?.setExtracting(request)
            }
            return et
        }
        return null
    }

    override fun sendKeyEvent(event: KeyEvent): Boolean {
        return super.sendKeyEvent(event)
    }

    override fun setComposingText(text: CharSequence, newCursorPosition: Int): Boolean {
        //  这里也可以接收文本
        return super.setComposingText(text, newCursorPosition)
    }

    override fun beginBatchEdit(): Boolean {
        synchronized(this) {
            if (mBatchEditNesting >= 0) {
                mTextInputView?.beginBatchEdit()
                mBatchEditNesting++
                return true
            }
        }
        return false
    }

    override fun endBatchEdit(): Boolean {
        synchronized(this) {
            if (mBatchEditNesting > 0) {
                // When the connection is reset by the InputMethodManager and reportFinish
                // is called, some endBatchEdit calls may still be asynchronously received from the
                // IME. Do not take these into account, thus ensuring that this IC's final
                // contribution to mTextView's nested batch edit count is zero.
                mTextInputView?.endBatchEdit()
                mBatchEditNesting--
                return mBatchEditNesting > 0
            }
        }
        return false
    }

    fun endComposingRegionEditInternal() {
        // The ContentCapture service is interested in Composing-state changes.
        mTextInputView?.notifyContentCaptureTextChanged()
    }

    override fun closeConnection() {
        super.closeConnection()
        synchronized(this) {
            while (mBatchEditNesting > 0) {
                endBatchEdit()
            }
            // Will prevent any further calls to begin or endBatchEdit
            mBatchEditNesting = -1
        }
    }

    override fun clearMetaKeyStates(states: Int): Boolean {
        var content = editable
        val listener: KeyListener? = mTextInputView?.keyListener
        if (listener != null) {
            try {
                listener.clearMetaKeyState(mTextInputView, content, states)
            } catch (e: AbstractMethodError) {
                // This is an old listener that doesn't implement the
                // new method.
            }
        }
        return true
    }


    override fun commitCompletion(text: CompletionInfo): Boolean {
        if (DEBUG) Log.v(
            TAG,
            "commitCompletion $text"
        )
        return false
    }

    /**
     * Calls the [android.widget.TextView.onCommitCorrection] method of the associated TextView.
     */
    override fun commitCorrection(correctionInfo: CorrectionInfo): Boolean {
        if (DEBUG) Log.v(
            TAG,
            "commitCorrection $correctionInfo"
        )
        return true
    }

    override fun performEditorAction(actionCode: Int): Boolean {
        if (DEBUG) Log.v(
            TAG,
            "performEditorAction $actionCode"
        )
        mTextInputView?.onEditorAction(actionCode)
        return true
    }
    //键盘呼出菜单行为
    override fun performContextMenuAction(id: Int): Boolean {
        if (DEBUG) Log.v(
            TAG,
            "performContextMenuAction $id"
        )
        return true
    }


    override fun performSpellCheck(): Boolean {
        return false  //拼写检查
    }

    override fun performPrivateCommand(action: String, data: Bundle): Boolean {
        return true
    }

    override fun commitText(
        text: CharSequence,
        newCursorPosition: Int
    ): Boolean {
        return if (mTextInputView == null) {
            super.commitText(text, newCursorPosition)
        } else super.commitText(text, newCursorPosition)
    }

}
